<template>
  <div v-loading="pageLoading" class="game_brackets">
    <header class="game_modal_header ">场次对阵</header>
    <div class="modal_shadow gl_searchBox">
      <!-- 查询 -->
      <div class="demo-input-suffix">
        <el-row :gutter="20">
          <el-col :md="6" :lg="4">
            <p>时间</p>
            <el-select v-model="api_GET_GameResultQO.StartDate" size="small" placeholder="请选择赛事日期" filterable @change="changeGameDate()">
              <el-option v-for="item in gameDayList" :key="item.date" :value="item.date" :label="item.date && item.date.substring(0, 10)" />
            </el-select>
          </el-col>
          <el-col :md="6" :lg="4">
            <p>场地</p>
            <el-select v-model="api_GET_GameResultQO.LocationCode" size="small" placeholder="请选择场地" filterable @change="changeLocation()">
              <el-option v-for="item in gameLocationList" :key="item.code" :value="item.code" :label="item.name" />
            </el-select>
          </el-col>
          <el-col :md="6" :lg="4">
            <p>单元</p>
            <el-select v-model="api_GET_GameResultQO.SessionId" size="small" placeholder="请选择单元" filterable @change="getGameResultList()">
              <el-option v-for="item in gameSessionList" :key="item.id" :value="item.id" :label="handleShowSessionDate(item)" />
            </el-select>
          </el-col>
          <el-col :md="6" :lg="4">
            <p>状态</p>
            <el-select v-model="api_GET_GameResultQO.StatusCode" size="small" placeholder="请选择赛事类型" filterable @change="getGameResultList()">
              <el-option value="" label="全部" />
              <template v-for="item in dict.status">
                <template v-if="item.code==='Running' || item.code==='Scheduled' || item.code==='UnOfficial'">
                  <el-option :key="item.code" :value="item.code" :label="item.value" />
                </template>
              </template>
            </el-select>
          </el-col>
          <!-- <el-col :span="6" :lg="4">
            <p>类型</p>
            <el-select v-model="gameType" size="small" placeholder="请选择赛事类型" @change="getGameResultList()">
              <el-option value="All" label="全部" />
              <el-option value="Competitive" label="淘汰赛" />
              <el-option value="NoneCompetitive" label="打分赛" />
            </el-select>
          </el-col> -->
          <el-col :md="8" :lg="6">
            <el-input v-model="search" prefix-icon="el-icon-search" placeholder="姓名/机构名/项目名称" size="small" clearable @change="getGameResultList()" />
          </el-col>
          <!-- <el-col :span="6" :lg="4" class="search_btn">
            查看对阵表
            <el-button class="downloadBracket" size="small" :loading="downloadBracketLoadding" @click="downloadBracket('Bracket')">查看对阵表</el-button>
          </el-col> -->
        </el-row>
      </div>
      <div class="gl_mt_15">
        <el-tabs v-if="competitiveTableData.length > 0 || noneCompetitiveTableData.length > 0" v-model="activeName">
          <el-tab-pane v-if="gameType !== 'NoneCompetitive' && competitiveTableData.length > 0" label="淘汰赛" name="1">
            <competitive :competitive-table-data="competitiveTableData" @refreshPage="getResultWidthCompetitiveList()" />
          </el-tab-pane>
          <el-tab-pane v-if="gameType !== 'Competitive' && noneCompetitiveTableData.length > 0" label="打分赛" name="2">
            <noneCompetitive :none-competitive-table-data="noneCompetitiveTableData" @refreshPage="getResultWidthNoneCompetitiveList()" />
          </el-tab-pane>
        </el-tabs>
        <div v-else class="gl_mt_15">
          <el-table size="mini" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import competitive from './competitive';
import noneCompetitive from './noneCompetitive';
import { mapState, mapActions } from 'vuex';
import defaultPersonImg from '@/assets/images/face_default.png';
import { Api_GET_GameResultQO } from '@/lib/form/events';
import {
  api_GET_EventsManagementCompetitionDay,
  api_GET_EventsManagementCompetitionSession,
  api_GET_EventsManagementCompetitionLocation,
  api_GET_EventsManagementUnitResultCompetitiveList,
  api_GET_EventsManagementUnitResultNoneCompetitiveList
} from '@/extend/api/gameswaggerApi/app';
export default {
  components: {
    competitive,
    noneCompetitive
  },
  data() {
    return {
      activeName: '1',
      pageLoading: false,
      defaultPersonImg: defaultPersonImg,
      search: '',
      api_GET_GameResultQO: new Api_GET_GameResultQO(),
      competitiveTableData: [],
      noneCompetitiveTableData: [],
      // 赛事日期
      gameDayList: [],
      // 赛事单元
      gameSessionList: [],
      // 比赛场地
      gameLocationList: [],
      // 赛事类型
      gameType: 'All' // 竞技类('Competitive') 、非竞技类('NoneCompetitive')、全部('')
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.gameId = this.$route.query.id;
    this.getDict();
    Promise.all([this.getGameDayList(), this.getGameLocationList()]).then(() => {
      this.api_GET_GameResultQO.StartDate = this.gameDayList[0] && this.gameDayList[0].date || '';
      this.api_GET_GameResultQO.LocationCode = this.gameLocationList[0] && this.gameLocationList[0].code || '';
      this.getGameSessionList().then(() => {
        this.api_GET_GameResultQO.SessionId = this.gameSessionList[0] && this.gameSessionList[0].id || '';
        if (this.api_GET_GameResultQO.SessionId) {
          this.getGameResultList();
        }
      });
    });
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取成绩列表
    getGameResultList() {
      if (!this.api_GET_GameResultQO.SessionId) {
        this.competitiveTableData = [];
        this.noneCompetitiveTableData = [];
        this.$message({ type: 'warning', message: '单元选择不能为空！' });
        return;
      }
      this.pageLoading = true;
      if (this.gameType !== 'NoneCompetitive') {
        this.activeName = '1';
        this.getResultWidthCompetitiveList();
      }
      if (this.gameType !== 'Competitive') {
        this.activeName = '2';
        this.getResultWidthNoneCompetitiveList();
      }
    },
    // 查询竞技类比赛成绩
    getResultWidthCompetitiveList() {
      var that = this;
      const param = {
        SessionId: that.api_GET_GameResultQO.SessionId,
        StatusCode: that.api_GET_GameResultQO.StatusCode,
        Search: that.search
      };
      api_GET_EventsManagementUnitResultCompetitiveList(param).then(res => {
        let competitiveData = res.items || [];
        that.activeName = competitiveData.length > 0 ? '1' : '2';
        if (competitiveData.length > 0) {
          competitiveData = competitiveData.map(item => {
            if (item.memberNamesA) {
              let strA = '';
              for (let a = 0; a < item.memberNamesA.length; a++) {
                const atem = item.memberNamesA[a];
                strA = strA + atem;
                if (a !== item.memberNamesA.length - 1) {
                  strA = strA + '/' + ' ';
                }
              }
              item.memberNamesA = strA;
            }
            if (item.memberNamesB) {
              let strB = '';
              for (let b = 0; b < item.memberNamesB.length; b++) {
                const btem = item.memberNamesB[b];
                strB = strB + btem;
                if (b !== item.memberNamesB.length - 1) {
                  strB = strB + '/' + ' ';
                }
              }
              item.memberNamesB = strB;
            }
            return { ...item };
          });
        }
        that.competitiveTableData = competitiveData;
        that.pageLoading = false;
        // this.total = res.totalCount;
        // this.competitiveTableData = this.competitiveTableData.filter(item => item.playerNameA && item.playerNameB);
      }, () => {
        that.pageLoading = false;
        that.$message({ type: 'error', message: '获取成绩列表失败！' });
      });
    },
    // 查询非竞技类比赛成绩
    getResultWidthNoneCompetitiveList() {
      var that = this;
      const param = {
        SessionId: that.api_GET_GameResultQO.SessionId,
        StatusCode: that.api_GET_GameResultQO.StatusCode,
        Search: that.search
      };
      api_GET_EventsManagementUnitResultNoneCompetitiveList(param).then(res => {
        let noneCompetitiveData = res.items || [];
        if (noneCompetitiveData.length > 0) {
          noneCompetitiveData = noneCompetitiveData.map(item => {
            for (let i = 0; i < item.unitResultList.length; i++) {
              const list = item.unitResultList[i];
              if (list.memberNames) {
                let str = '';
                for (let j = 0; j < list.memberNames.length; j++) {
                  const jtem = list.memberNames[j];
                  str = str + jtem;
                  if (j !== list.memberNames.length - 1) {
                    str = str + '/' + ' ';
                  }
                }
                list.memberNames = str;
              }
            }
            return { ...item };
          });
        }
        that.noneCompetitiveTableData = that.handleunitResultList(noneCompetitiveData);
        // that.total = res.totalCount;
        that.pageLoading = false;
      }, () => {
        that.pageLoading = false;
        that.$message({ type: 'error', message: '获取成绩列表失败！' });
      });
    },
    // 处理非竞技成绩
    handleunitResultList(tableData) {
      if (tableData.length > 0) {
        var arr = [];
        for (var i = 0; i < tableData.length; i++) {
          var item = tableData[i];
          if (item.unitResultList.length < 2) {
            var ktem0 = JSON.parse(JSON.stringify(item));
            ktem0.unitResultList = false;
            ktem0 = Object.assign(ktem0, item.unitResultList[0]);
            arr.push(ktem0);
          } else {
            var ktem1 = JSON.parse(JSON.stringify(item));
            ktem1.unitResultList = true;
            ktem1 = Object.assign(ktem1, item.unitResultList[0]);
            var ktem2 = JSON.parse(JSON.stringify(item));
            ktem2.unitResultList = true;
            ktem2 = Object.assign(ktem2, item.unitResultList[1]);
            arr.push(ktem1);
            arr.push(ktem2);
          }
        }
        return arr;
      } else {
        return [];
      }
    },
    // 获取赛事日期列表
    getGameDayList() {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementCompetitionDay({ competitionId: this.gameId }).then(res => {
          this.gameDayList = res.items || [];
          resolve(res.items);
        }, error => {
          this.$message({ type: 'error', message: '获取赛事日期列表失败！' });
          reject(error);
        });
      });
    },
    // 获取赛事单元列表 - 单元数据依赖场地和赛事日期
    getGameSessionList() {
      return new Promise((resolve, reject) => {
        this.CompetitionSessionQO = {};
        this.CompetitionSessionQO.CompetitionId = this.gameId;
        this.CompetitionSessionQO.Day = this.api_GET_GameResultQO.StartDate;
        this.CompetitionSessionQO.LocationCode = this.api_GET_GameResultQO.LocationCode;
        api_GET_EventsManagementCompetitionSession(this.CompetitionSessionQO).then(res => {
          console.log(res);
          // const _item = this.formatSessionListByTime(res.items);
          this.gameSessionList = res.items;
          resolve(res.items);
        }, error => {
          this.$message({ type: 'error', message: '获取赛事单元列表失败！' });
          reject(error);
        });
      });
    },
    // 获取场地列表
    getGameLocationList() {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementCompetitionLocation({ competitionId: this.gameId }).then(res => {
          this.gameLocationList = res.items || [];
          resolve(res.items);
        }, error => {
          this.$message({ type: 'error', message: '获取场地列表失败！' });
          reject(error);
        });
      });
    },
    // 改变赛事日期
    changeGameDate() {
      this.getGameSessionList().then(() => {
        this.api_GET_GameResultQO.SessionId = this.gameSessionList[0] && this.gameSessionList[0].id || '';
        this.getGameResultList();
        // if (this.api_GET_GameResultQO.SessionId) {
        //   this.getGameResultList();
        // } else {
        //   this.competitiveTableData = [];
        //   this.noneCompetitiveTableData = [];
        // }
      });
    },
    // 改变场地
    changeLocation() {
      // this.api_GET_GameResultQO.LocationCode = locationItem.code;
      this.getGameSessionList().then(() => {
        this.api_GET_GameResultQO.SessionId = this.gameSessionList[0] && this.gameSessionList[0].id || '';
        // if (this.api_GET_GameResultQO.SessionId) {
        this.getGameResultList();
        // }
      });
    },
    // 处理单元中日期的展示
    handleShowSessionDate(sessionItem) {
      const _startTime = sessionItem.startTime && sessionItem.startTime.substring(11, 16);
      const _endTime = sessionItem.endTime && sessionItem.endTime.substring(11, 16);
      return `${sessionItem.type}(${_startTime}-${_endTime})`;
    },
    // 获取静态图片地址
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultPersonImg;
    }
  }
};
</script>
<style scoped>
.modal_shadow {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0px 10px 30px 0px rgba(0,0,0,0.10);
  padding: 20px;
}
.game_modal_header {
  position: relative;
  box-sizing: border-box;
  height: 40px;
  padding-left: 20px;
  margin-bottom: 14px;
  line-height: 40px;
  color: #353434;
  font-weight: bold;
  font-size: 20px;
}
.game_modal_header::after {
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 8px;
  height: 40px;
  background-color: #E02020;
  border-radius: 4px;
  content: "";
}
.downloadBracket{
  background:#31456C;
  color:#fff;
  border-radius: 8px;
}
.downloadBracket:hover{
  background:#4969a9;
  color: #fff;
}
.game_brackets .el-table th.is-leaf, .el-table td{
  background: #fafafa;
  border-right: none;
  height: 54px;
  font-size: 14px;
}
.gl_searchBox p {
  font-size: 14px;
  width: 20%;
  display: inline-block;
}
.gl_searchBox .el-select {
  width: 80%;
  display: inline-block;
}
.gl_searchBox .search_btn{
  height: auto;
  line-height: inherit;
}
.el-tabs /deep/ .el-tabs__header .el-tabs__item.is-active {
  color: #e02020;
}
.el-tabs /deep/ .el-tabs__header .el-tabs__item:hover {
  color: #e02020;
}
.el-tabs /deep/ .el-tabs__active-bar {
  background-color: #e02020;
}
</style>
